#include "stdafx.h"
#include "Utility.h"
#include "Player.h"
#include "Configs.h"
#include "Animation.h"
#include "Game.h"
#include "InputSniffer.h"
#include "MemTrack.h"

namespace bs
{
	Player::Player(Game& game)
		: game(game), leftDir(false), anim(NULL)
	{
		this->fireTimer.SetPos(1, game.GetWinHeight()-fireTimer.GetHeight()-1);
		this->fireTimer.AttachListener(this);
	}

	Player::~Player()
	{
		SAFE_DELETE(this->anim);
	}

	void Player::OnTimeUp(int id)
	{
		this->fireEnable = true;
	}

	bool Player::Init(const PlayerCfg& cfg)
	{
		this->EnabelMaxVel(true);
		this->EnableBounds(true);
		this->EnableMoveOut(false);

		this->maxVx = cfg.maxVx;
		this->friX = cfg.friX;
		this->x = cfg.x;
		this->y = cfg.y;
		this->accX = cfg.accX;
		this->bullet = cfg.bullet;
		this->explode = cfg.explode;
		this->explodeSnd = cfg.explodeSnd;

		this->fireTimer.SetTime(cfg.fireDelay);
		this->fireEnable = true;

		this->anim = new Animation;
		this->anim->LoadFile(cfg.image.c_str(), cfg.row, cfg.col);
		this->anim->SetAniSeq(0, cfg.row*cfg.col-1);
		this->anim->SetPos(this->x, this->y);
		this->anim->Start();

		this->w = this->anim->GetWidth();
		this->h = this->anim->GetHeight();

		return true;
	}

	void Player::Update(const InputSniffer& input, int elapse, float speedFactor)
	{
		this->fireTimer.Update(elapse);

		if(input.IsKeyDown(VK_LEFT))
		{
			this->SetAccel(-this->accX, 0.0f);
			this->anim->Resume();

			if(!this->leftDir)
			{
				this->anim->ReverseAniSeq();
				this->leftDir = true;
			}
		}
		else if(input.IsKeyDown(VK_RIGHT))
		{
			this->SetAccel(this->accX, 0.0f);
			this->anim->Resume();

			if(this->leftDir)
			{
				this->anim->ReverseAniSeq();
				this->leftDir = false;
			}
		}
		else
		{
			this->SetAccel(0.0f, 0.0f);
			this->anim->Pause();
		}

		if(input.IsKeyDown(VK_SPACE) && this->fireEnable)
		{
			this->game.AddBullet(this->bullet.c_str(), *this, this->leftDir, false);
			this->fireEnable = false;

			this->fireTimer.Start();
		}

		this->DoMove(speedFactor);
		this->anim->SetPos(this->x, this->y);
		this->anim->Update(elapse, speedFactor);
	}

	void Player::Draw(HDC dc)
	{
		this->anim->Draw(dc);
		this->fireTimer.Draw(dc);
	}

}
